package com.gitee.huxing.course.netty.gateway.adapter;

import com.gitee.huxing.course.netty.gateway.factory.BusinessFactory;
import com.gitee.huxing.course.netty.threadpool.ThreadPool;
import com.gitee.huxing.course.netty.util.SpringBeanContext;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @Description: 网关服务请求
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.netty.servce.adpater
 * @ClassName: ServiceChannelHandlerAdpater
 * @Author: huxing
 * @DateTime: 2021-08-20 下午6:51
 */
@Slf4j
@SuppressWarnings("all")
public class GatewayChannelHandlerAdapter extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        ThreadPool.getInstance().getExecutor(2).execute(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("查看一下ctx的情况: {}", ctx.channel().remoteAddress().toString());
                    FullHttpRequest request = (FullHttpRequest) msg;
                    log.info("网关接收到请求消息: {}", request.content()
                            .toString(StandardCharsets.UTF_8));
                    // TODO: 这里通过容器注入来获取处理对象
                    BusinessFactory factory = (BusinessFactory)SpringBeanContext
                            .getBean("requestFactory");
                    // 流程处理
                    factory.processBussiness(request, ctx);
                } catch (Exception ex){
                    ex.printStackTrace();
                } finally {
                    // 最终释放对象空间
                    ReferenceCountUtil.release(msg);
                }
            }
        });
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
       ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("这里打印异常记录信息:::" + "exceptionCaught");
        super.exceptionCaught(ctx, cause);
    }

}

